--[[
    聊天气泡显示组件，支持快捷文本和表情
]]--

local blaze = require "blaze"
local app = require "app"
local gamelib = require "club.threecard.gamelib"
local chat = gamelib.chat

local M = gamelib.ui.element()

-- 设置聊天气泡的朝向，默认是FACING_RIGHT
-- facing gamelib.chat.FACING_XXX
function M:set_chat_facing(facing)
    self.facing = facing
end

-- 播放聊天消息表现
-- msg game.store.chat里的单个message
function M:chat(msg)
    self:lazy("on_chat", msg)
end

local function show_bubble_emoji(self, msg)
    if not self.bubble_emoji then
        local BubbleEmoji = require "club.threecard.gamelib.UI.Chat.BubbleEmoji"
        self.bubble_emoji = BubbleEmoji.new()
        self.bubble_emoji:load()
    end
    self.bubble_emoji:set_parent(self.center_root)
    self.bubble_emoji:show(msg.emoji_id)
end

local function show_bubble_text(self, msg)
    if self.facing == chat.FACING_LEFT then
        if not self.bubble_text_left then
            local BubbleText = require "club.threecard.gamelib.UI.Chat.BubbleText"
            self.bubble_text_left = BubbleText.new_left()
            self.bubble_text_left:set_parent(self.left_root)
            self.bubble_text_left:load()
        end
        self.bubble_text_left:show(msg.text)
    else
        if not self.bubble_text_right then
            local BubbleText = require "club.threecard.gamelib.UI.Chat.BubbleText"
            self.bubble_text_right = BubbleText.new_right()
            self.bubble_text_right:set_parent(self.right_root)
            self.bubble_text_right:load()
        end
        self.bubble_text_right:show(msg.text)
    end
end

function M:on_chat(msg)
    if msg.msg_type == chat.MSG_TYPE_EMOJI then
        show_bubble_emoji(self, msg)
    elseif msg.msg_type == chat.MSG_TYPE_PHRASE then
        show_bubble_text(self, msg)
    else
        -- 纯文本聊天消息不显示
    end
end

function M:on_set_gameobject()
    self:super("on_set_gameobject")
    self.loaded = true
end

function M:on_release()
    self:super("on_release")
    if self.bubble_text_left then
        self.bubble_text_left:release()
    end
    if self.bubble_text_right then
        self.bubble_text_right:release()
    end
    if self.bubble_emoji then
        self.bubble_emoji:release()
    end
end

return M